package com.aohj.patchmaster.popup.actions;

import java.util.ArrayList;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.aohj.patchmaster.Files;
import com.aohj.patchmaster.Message;
import com.aohj.patchmaster.PatchMaster;

public class PathAction implements IObjectActionDelegate {
	private Shell shell;
	private TreeSelection selection = null;

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof TreeSelection) {
			this.selection = (TreeSelection) selection;
		}
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		String title = Message.COPY_PATH_TITLE;
		String message = Message.COPY_PATH_MESSAGE;
		try {
			if (!(selection.getFirstElement() instanceof IFile))
				return;
			IFolder patchMasterRoot = Files.newFolder(
					Files.getProject((IFile) selection.getFirstElement()),
					PatchMaster.ROOT);
			ArrayList<IFile> files = new ArrayList<IFile>();
			for (Object object : selection.toArray()) {
				if (!(object instanceof IFile))
					continue;
				if (Files.getAbsolutePath((IFile) object).startsWith(
						Files.getAbsolutePath(patchMasterRoot)))
					continue;
				files.add((IFile) object);
			}
			if (files.size() == 0)
				return;
			StringBuilder sb = new StringBuilder();
			sb.append(PatchMaster.LINE_SEPARATOR);
			sb.append(PatchMaster.LINE_COMMENT);
			for (IFile file : files) {
				sb.append(PatchMaster.LINE_SEPARATOR);
				sb.append(Files.getProjectRelativePath(file));
			}
			sb.append(PatchMaster.LINE_SEPARATOR);
			byte[] bytes = String.valueOf(sb).getBytes(PatchMaster.CHARSET);
			Files.write(Files.getFile(patchMasterRoot, PatchMaster.COPY_PATH),
					bytes);
			Files.write(Files.getFile(patchMasterRoot, PatchMaster.PATCH_PATH),
					bytes);
		} catch (Exception e) {
			message = String.valueOf(e);
		}
		MessageDialog.openInformation(shell, title, message);
	}
}